package com.blunka.framework.client.ui.dialog;

import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowEvent;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Vector;
import javax.swing.AbstractButton;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JToolBar;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea;

import com.blunka.framework.client.constants.ImageConstant;
import com.blunka.framework.client.utils.DesignUtils;

@SuppressWarnings("serial")
public class RangConfigDialog extends JDialog implements ActionListener, ItemListener {
	private static Logger logger = Logger.getLogger(RangConfigDialog.class);

	public static final String CLEAR = "0";

	public static final String CONSANT = "1";

	public static final String SQL = "2";

	private JPanel framePanel;

	private JPanel bottomPanel;

	private JButton okButton;

	private JButton noButton;

	private JRadioButton clearRadio;

	private JRadioButton constRadio;

	private JRadioButton sqlRadio;

	private ButtonGroup buttonGroup;

	private JPanel radioPanel;

	private JPanel setPanel;

	private RSyntaxTextArea sqlArea;

	private JTable tablePanel;

	private TableModel attrModel;

	private JScrollPane areaScrollpanel;

	private JScrollPane tableScrollPanel;

	private CardLayout card;

	private JToolBar tableToolBar;

	private String returnConfig;

	public static final Object[] ATTRIBUTETITLE = { "属性值", "显示值" };

	public static final Object[][] ATTRIBUTEDATA = { { "", "" } };

	public RangConfigDialog() {
		setSize(400, 330);

		setTitle("业务模式设置");

		initDialog();
	}

	public void setReturnConfig(Object returnConfig) {
		this.returnConfig = String.valueOf(returnConfig == null ? "" : returnConfig);
	}

	public String getReturnConfig() {
		return this.returnConfig;
	}

	private void initDialog() {
		setLayout(new BorderLayout());
		this.framePanel = new JPanel();
		this.bottomPanel = new JPanel();
		add(this.framePanel, "Center");
		add(this.bottomPanel, "South");

		this.framePanel.setLayout(new BorderLayout());

		this.clearRadio = new JRadioButton("清空");

		this.clearRadio.setActionCommand("0");
		this.clearRadio.addItemListener(this);

		this.constRadio = new JRadioButton("常量");
		this.constRadio.setSelected(true);

		this.constRadio.setActionCommand("1");
		this.constRadio.addItemListener(this);

		this.sqlRadio = new JRadioButton("SQL数值");

		this.sqlRadio.setActionCommand("2");
		this.sqlRadio.addItemListener(this);

		this.buttonGroup = new ButtonGroup();

		this.buttonGroup.add(this.clearRadio);

		this.buttonGroup.add(this.constRadio);

		this.buttonGroup.add(this.sqlRadio);

		this.radioPanel = new JPanel();
		this.radioPanel.setLayout(new GridLayout(1, 3));
		this.radioPanel.add(this.clearRadio);
		this.radioPanel.add(this.constRadio);
		this.radioPanel.add(this.sqlRadio);

		this.framePanel.add(this.radioPanel, "North");

		this.setPanel = new JPanel();

		this.card = new CardLayout(5, 5);

		this.setPanel.setLayout(this.card);

		this.framePanel.add(this.setPanel, "Center");

		Box box_button = new Box(0);
		this.bottomPanel.add(box_button);
		this.okButton = new JButton("确   定");
		this.okButton.addActionListener(this);
		box_button.add(this.okButton);

		this.noButton = new JButton("取   消");
		this.noButton.addActionListener(this);
		box_button.add(this.noButton);

		initTypeModel();
	}

	public void initTypeModel() {
		this.attrModel = new DefaultTableModel(ATTRIBUTEDATA, ATTRIBUTETITLE);

		this.tablePanel = new JTable(this.attrModel);
		tablePanel.setRowHeight(25);

		this.tableScrollPanel = new JScrollPane(this.tablePanel);

		JPanel panelTable = new JPanel();

		panelTable.setBorder(BorderFactory.createLineBorder(Color.gray));

		panelTable.setLayout(new BorderLayout());

		panelTable.add(this.tableScrollPanel, "Center");

		this.tableToolBar = new JToolBar();

		this.tableToolBar.add(createAddButton());

		this.tableToolBar.add(createDeleteButton());

		panelTable.add(this.tableToolBar, "North");

		this.sqlArea = new RSyntaxTextArea();
		sqlArea.setSyntaxEditingStyle(RSyntaxTextArea.SYNTAX_STYLE_SQL);

		//this.sqlArea.setFont(new Font("黑体", 1, 14));

		//this.sqlArea.setForeground(Color.BLUE);

		this.areaScrollpanel = new JScrollPane(this.sqlArea);

		this.setPanel.add(new JPanel(), "0");

		this.setPanel.add(panelTable, "1");

		this.setPanel.add(this.areaScrollpanel, "2");

		this.card.show(this.setPanel, "1");
	}

	private JButton createAddButton() {
		JButton button = new JButton("新增");
		button.setToolTipText("");
		button.setIcon(new ImageIcon(ImageConstant.ADD));
		button.addActionListener(addConfigRow());
		return button;
	}

	private JButton createDeleteButton() {
		JButton button = new JButton("删除");
		button.setToolTipText("");
		button.setIcon(new ImageIcon(ImageConstant.DELETE));
		button.addActionListener(deleteConfigRow());
		return button;
	}

	public void actionPerformed(ActionEvent e) {
		if (e.getSource() == this.okButton) {
			if (saveConfig()) {
				dispose();
			}

		} else if (e.getSource() == this.noButton) {
			setReturnConfig(getReturnConfig());

			dispose();
		}
	}

	public void itemStateChanged(ItemEvent e) {
		String choice = this.buttonGroup.getSelection().getActionCommand();

		if (choice.equals("0")) {
			this.card.show(this.setPanel, "0");

			//clearSetConfig();
		} else if (choice.equals("1")) {
			this.card.show(this.setPanel, "1");
		} else if (choice.equals("2")) {
			this.card.show(this.setPanel, "2");
		}
	}

	public void clearSetConfig() {
		this.sqlArea.setText("");

		DefaultTableModel model = (DefaultTableModel) this.tablePanel.getModel();

		int modelSize = model.getRowCount();

		for (int i = 1; i < modelSize; i++) {
			model.removeRow(0);
		}

		this.tablePanel.setValueAt("", 0, 0);

		this.tablePanel.setValueAt("", 0, 1);
	}

	private ActionListener addConfigRow() {
		ActionListener action = new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				DefaultTableModel model = (DefaultTableModel) RangConfigDialog.this.tablePanel.getModel();

				Vector<String> v = new Vector<String>();

				v.add("");

				v.add("");

				model.addRow(v);
			}

		};
		return action;
	}

	private ActionListener deleteConfigRow() {
		ActionListener action = new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (RangConfigDialog.this.tablePanel.getSelectedRow() < 0) {
					return;
				}
				int returnNum = DesignUtils.showConfirm(null, "确定需要删除该记录？");

				if (returnNum != 0) {
					return;
				}
				DefaultTableModel model = (DefaultTableModel) RangConfigDialog.this.tablePanel.getModel();

				model.removeRow(RangConfigDialog.this.tablePanel.getSelectedRow());
			}

		};
		return action;
	}

	private boolean saveConfig() {
		String configType = this.buttonGroup.getSelection().getActionCommand();
		JSONObject rootObject = new JSONObject();

		JSONObject RangConfigObject = new JSONObject();

		RangConfigObject.put("configType", configType);

		if (configType.equals("1")) {
			int count = this.tablePanel.getRowCount();

			JSONArray ConstantArray = new JSONArray();

			for (int i = 0; i < count; i++) {
				String key = String.valueOf(this.tablePanel.getValueAt(i, 0));

				String value = String.valueOf(this.tablePanel.getValueAt(i, 1));

				JSONObject ConstantObject = new JSONObject();

				ConstantObject.put(key, value);

				ConstantArray.add(ConstantObject);
			}

			RangConfigObject.put("Config", ConstantArray);
		} else if (configType.equals("2")) {
			JSONObject configObject = new JSONObject();

			configObject.put("Sql", this.sqlArea.getText().trim());

			RangConfigObject.put("Config", configObject);
		}

		rootObject.put("RangConfig", RangConfigObject);

		String returnConfig = rootObject.toString();
		/*if (returnConfig.indexOf("'") >= 0) {
			DesignUtils.showMessage(null, "选择范围属性包含非法字符“引号”！", "系统提示", 1);
			return false;
		}*/
		setReturnConfig(rootObject.toString());
		return true;
	}

	private void fillRangConfig(ButtonGroup group, JTextArea area, JTable table) {
		try {
			JSONArray rangArray = JSONArray.fromObject("[" + this.returnConfig + "]");

			if ((rangArray == null) || (rangArray.isEmpty())) {
				return;
			}
			JSONObject rootJson = rangArray.getJSONObject(0);

			JSONObject rangConfig = rootJson.getJSONObject("RangConfig");

			String configType = rangConfig.getString("configType");

			if ("1".equals(configType)) {
				selectRadioButton(group, "1");
				JSONArray configArray = rangConfig.getJSONArray("Config");

				for (int i = 0; i < configArray.size(); i++) {
					JSONObject c = configArray.getJSONObject(i);

					Iterator it = c.keys();

					String key = "";
					String value = "";
					while (it.hasNext()) {
						key = (String) it.next();
						value = c.getString(key);
					}

					if (i == 0) {
						table.setValueAt(key, 0, 0);

						table.setValueAt(value, 0, 1);
					} else {
						DefaultTableModel model = (DefaultTableModel) table.getModel();

						Vector<String> v = new Vector();

						v.add(key);

						v.add(value);

						model.addRow(v);
					}
				}
			} else if ("2".equals(configType)) {
				selectRadioButton(group, "2");

				JSONObject sqlObject = rangConfig.getJSONObject("Config");

				String sql = sqlObject.getString("Sql");

				this.sqlArea.setText(sql);
			} else {
				selectRadioButton(group, "0");
			}

		} catch (Exception e) {
			logger.error("解析json数组异常", e);
		}
	}

	private void selectRadioButton(ButtonGroup group, String label) {
		Enumeration<AbstractButton> elements = group.getElements();

		while (elements.hasMoreElements()) {
			JRadioButton radio = (JRadioButton) elements.nextElement();

			String radioLabel = radio.getActionCommand();

			if (radioLabel.equals(label)) {
				radio.setSelected(true);

				break;
			}
		}
	}

	public void readConfig(Object config) {
		if (config == null) {
			return;
		}
		setReturnConfig(config);

		fillRangConfig(this.buttonGroup, this.sqlArea, this.tablePanel);
	}

	protected void processWindowEvent(WindowEvent e) {
		if (e.getID() == 201) {
			setReturnConfig(getReturnConfig());

			dispose();
		}
	}
}